//index.js
//获取应用实例

var sourceType = [
  ['camera'],
  ['album'],
  ['camera', 'album']
]
var sizeType = [
  ['compressed'],
  ['original'],
  ['compressed', 'original']
]
var app = getApp();
var util = require('../../../utils/util.js');
var applet_park_api_url = app.globalData.applet_park_api_url;

Page({
  data: {
    imageList: [],
    pics: [],
    workid: '',
    comremark: '',
    currenttext: 10,
    starClassNum: 5,
    starDesc: '非常满意，无可挑剔',
    stars: [{
      lightImg: '../../images/star_light.png',
      blackImg: '../../images/star_black.png',
      flag: 1,
      message: '非常不满意，各方面都很差'
    }, {
      lightImg: '../../images/star_light.png',
      blackImg: '../../images/star_black.png',
      flag: 1,
      message: '不满意，比较差'
    }, {
      lightImg: '../../images/star_light.png',
      blackImg: '../../images/star_black.png',
      flag: 1,
      message: '一般，还要改善'
    }, {
      lightImg: '../../images/star_light.png',
      blackImg: '../../images/star_black.png',
      flag: 1,
      message: '比较满意，仍要改善'
    }, {
      lightImg: '../../images/star_light.png',
      blackImg: '../../images/star_black.png',
      flag: 1,
      message: '非常满意，无可挑剔'
    }],
    assessLists: ['不认识', '其他',]
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  delect(e) {

    var pics = this.data.pics;

    var index = e.currentTarget.dataset.idx;
    pics.splice(index, 1);
    this.setData({
      pics: pics
    });
  },
  onLoad: function (options) {
    if (options.workid) {
      this.setData({
        workid: options.workid
      })
    }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  starClick: function (e) {
    var that = this;
    for (var i = 0; i < that.data.stars.length; i++) {
      var allItem = 'stars[' + i + '].flag';
      that.setData({
        [allItem]: 2
      })
    }
    var index = e.currentTarget.dataset.index;
    
    for (var i = 0; i <= index; i++) {
      var item = 'stars[' + i + '].flag';
      that.setData({
        [item]: 1
      })
    }
    // 评价星星文字说明
    let starClassNum = index + 1;
    this.setData({
      starDesc: this.data.stars[index].message,
      starClassNum: starClassNum
    })
    
  },
  getUserInfo: function (e) {
    
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  chooseImage_album: function (e) {

    var that = this;
    wx.chooseImage({
      sourceType: sourceType[2],
      count: 9,
      success: function (res) {
        var imgsrc = res.tempFiles;
        
        var pics = that.data.pics.concat(imgsrc);
        var imageList = that.data.imageList.concat(imgsrc);
        // for (var obj of res.tempFiles) {
        //   obj.showOrder = that.data.showOrder;
        //   that.data.showOrder++;
        // }
        that.setData({
          pics: pics,
          imageList: imageList
        })
      }
    })
  },
  submitRate() {
    var that = this;
    
    
    wx.request({
      url: "https://xxx/mobiletplus/index.php?act=login&op=send_wx",
      data: {
        "content": e.detail.formId,
        "starClassNum": that.data.customer_id
      },
      method: 'POST',
      success: function (res) {
        //util.showSuccess("设置成功")
        //

      },
      fail: function (e) {
        //util.showError("设置失败".e)
      }
    })
  },
  submit: function () {
    var that = this;
    var sources = '';
    wx.showLoading({
      title: '图片上传中',
      mask: true
    });
    var finished = true;
    
    // that.data.imageList = that.data.imageSingleList.concat(that.data.imageMultiList);
    for (var pic of that.data.imageList) {
      if (!pic.picUrl) { //false
        finished = false;
        break;
      }
    }

    if (finished) {
      wx.hideLoading();

      // wx.navigateBack();
      that.submitEEvaluations();
      return;
    }

    //用自执行函数,来解决循环内部的异步回调问题
    (function uploadImage(i) {
      if (i >= that.data.imageList.length) {
        return;
      }

      // var image = that.data.imageList[i];
      if (!that.data.imageList[i].picUrl && that.data.imageList[i].path) {
        var path = that.data.imageList[i].path;

        wx.uploadFile({
          url: applet_park_api_url + '/api/upload',
          filePath: path,
          name: 'files',
          success(res) {
            let response = JSON.parse(res.data);
            that.data.imageList[i].picUrl = "http://zjurainforest.com:9999" + response.data[0];

            sources = sources + response.data[0] + ",";
            // sources.push("http://zjurainforest.com:9999" + response.data[0])
            
            that.data.sources = sources;
            that.setData(that.data);
            
            //检测下其他图片有没有传完
            var allFinished = true;
            for (var pic of that.data.imageList) {
              if (!pic.picUrl) { //false
                allFinished = false;
                break;
              }
            }
            if (allFinished) { //全部传完了,则隐藏加载按钮并返回
              wx.hideLoading();
              //数据回传录车页面,返回
              that.submitEEvaluations();
              //wx.navigateBack();
            } else {
              uploadImage(i + 1);
            }
          },
          fail(res) {
            
          }
        })
      } else {
        uploadImage(i + 1);
      }
    })(0);
  },
  seclectDes(e) {
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      currenttext: index,
      comremark: item
    })
  },
  bindKeyInput: function (e) {
    this.data[e.currentTarget.dataset.inputname] = e.detail.value;
    this.setData(this.data);
  },

  submitEEvaluations() {
    var that = this;
    if (that.data.starClassNum <= 4) {
      if (!that.data.comremark) {
        wx.showToast({
          title: '请填写备注说明',
        })
        return

      }
    }
    var id = wx.getStorageSync("id");
    // wx.request({
    //   url: applet_park_api_url + '/api/repair/evaluations',
    //   data: {
    //     "repairId": that.data.workid,
    //     "starClassNum": that.data.starClassNum,
    //     "content": that.data.comremark,
    //     'assignorId': id,
    //     'consignorId': id,
    //     'sysUserId':id
    //   },
    //   method: 'POST',
    //   success: function(res) {
    //     if (res.data.code==0) {

    //       wx.showToast({
    //         title: '评价成功',
    //       })
    //       var pages = getCurrentPages();

    //       var prevPage = pages[pages.length - 2]; //上一个页面
    //       // prevPage.data.items = [];
    //       // prevPage.setData(prevPage.setDat);
    //       // prevPage.loadData();
    //       wx.navigateBack();
    //     } else {
    //       wx.showToast({
    //         title: '评价失败',
    //       })
    //     }
    //   },
    //   fail: function(e) {
    //     util.showError("设置失败".e)
    //   }
    // })

    requestDataparams('/api/repair/evaluations', {
      "repairId": that.data.workid,
      "starClassNum": that.data.starClassNum,
      "content": that.data.comremark,
      'assignorId': id,
      'consignorId': id,
      'sysUserId': id
    }, 'GET').then(res => {
      if (res.data.code == 0) {

        wx.showToast({
          title: '评价成功',
        })
        var pages = getCurrentPages();

        var prevPage = pages[pages.length - 2]; //上一个页面
        // prevPage.data.items = [];
        // prevPage.setData(prevPage.setDat);
        // prevPage.loadData();
        wx.navigateBack();
      } else {
        wx.showToast({
          title: '评价失败',
        })
      }
    }).catch(err => {
      
    });
  },
})